package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.WebVisitService;
import com.itheima.utils.CookieUtils;
import com.itheima.utils.IpUtils;
import com.itheima.utils.MD5Utils;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;

    @Value("${sign}")
    private String sign;

    @Autowired
    private WebVisitService webVisitService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String USER = "user";

    @PostMapping("/login")
    public Result login(@RequestBody Map userVO, HttpServletRequest request){
        System.out.println("进入登陆");
        String userName = (String) userVO.get("userName");
        String passWord = (String) userVO.get("passWord");
        String encode = MD5Utils.md5(passWord);
        User user = userService.findByUserName(userName);
        System.out.println(user.getPassWord());
        if (encode!=null && user.getPassWord()!=null && encode.equals(user.getPassWord())){//登陆成功
            //登陆成功，添加登陆次数
            user.setLoginCount(user.getLoginCount()+1);
            user.setLastLoginTime(new Date());
            String ipAddress = IpUtils.getIpAddr(request);
            user.setLastLoginIp(ipAddress);
            userService.update(user);
            //添加web访问记录
//            webVisitService.add(user);
            JwtBuilder jwtBuilder = Jwts.builder()
                    .setId(user.getUid())                                  //设置唯一编号
                    .setSubject("login")                            //设置主题
                    .setIssuedAt(new Date())                        //设置token生成时间
                    .claim("username", user.getUserName())      //将username放入token中,以便于后期从登陆信息中获取
                    .signWith(SignatureAlgorithm.HS256, sign);     //设置签名,使用HS256算法,并设置SecretKey字符串

            Map map = new HashMap();
            map.put("token", jwtBuilder.compact());
            //不设置过期时间,浏览器关闭后cookie丢弃 ,将token设置成cookie信息
            CookieUtils.setCookie("token", jwtBuilder.compact(),-1);
            //登陆成功，存入redis中
            redisTemplate.boundHashOps(USER).put(user.getUserName(),user);
            redisTemplate.expire(USER,60, TimeUnit.MINUTES);
            System.out.println("登陆成功");
            //将token返回给前段
            return new Result("success", map);
        }
        return new Result("fail","登陆失败,用户名或密码错误");
    }

    @PostMapping("/register")
    public Result register(@RequestBody Map userVO,HttpServletRequest request){
        String ip = IpUtils.getRealIp(request);
        Map<String, String> map = IpUtils.getOsAndBrowserInfo(request);
        String osName = (String)map.get("OS");
        String browserName = (String)map.get("BROWSER");
        userVO.put("ipSource",ip);
        userVO.put("os",osName);
        userVO.put("browser",browserName);
        boolean flag = userService.save(userVO);
        return new Result("fail","注册成功");
    }
}
